package com.nebula.controller;

import java.io.IOException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.nebula.common.Const;

public class BaseController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String methodStr = req.getParameter("method");

		if (StringUtils.isBlank(methodStr)) {
			methodStr = Const.METHOD_BLANK;
		}

		Class<? extends BaseController> clazz = this.getClass();

		try {
			if (methodStr.equals(Const.METHOD_BLANK)) {
				req.getSession().setAttribute("msg", "服务器无法响应该请求，请稍后重试！");
				resp.sendRedirect(Const.MESSAGE_PAGE);
			}else {
				Method method = clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
				Object result = method.invoke(this, req, resp);

				// 集中处理返回值响应
				if (result != null) {
					String str = (String) result;
					if (str.startsWith(Const.FORWARD)) {
						// 转发
						String path = getSubstring(str);
						req.getRequestDispatcher(path).forward(req, resp);
					} else if (str.startsWith(Const.REDIRECT)) {
						// 重定向
						String path = getSubstring(str);
						resp.sendRedirect(path);
					} else if (str.startsWith(Const.JSON)) {
						resp.setContentType("application/json");
						// 异步请求 返回json数据
						resp.getWriter().write(getSubstring(str));
					} else {
						resp.getWriter().println(str);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			req.getSession().setAttribute("msg", "程序异常，请稍后再试！");
			resp.sendRedirect(Const.MESSAGE_PAGE);
		}
	}

	private String getSubstring(String str) {
		return str.substring(str.indexOf(Const.FLAG) + 1);
	}
}
